<template>
  <div style="margin-top: 20px;">
    <el-form ref="form" :model="form" :rules="rules" label-position="top">
      <el-form-item v-show="docId" label="文档动态">
        <el-button size="mini" style="position: absolute;right: 0px;top: -50px;" type="danger" @click="make_question">新增问题</el-button>

        <div style="margin-left: 5px;border:1px black solid #DCDFE6;padding-left: 5px;padding-right: 5px;background: white;margin-left: 5px;">
          <div v-for="o in logs" :key="o.edit_time">
            <div class="bottom clearfix">
              <span style="width:200px;">{{ o.editor }}: </span>
              <el-tooltip
                v-show="!!o.params"
                v-clipboard:copy="o.params"
                v-clipboard:success="onCopy"
                v-clipboard:error="onError"
                class="item"
                effect="dark"
                content="拷贝参数"
                placement="right"
              >
                <i class="el-icon-document-copy " style="color: #409EFF;cursor: pointer;" />
              </el-tooltip>
              <span>{{ o.message }}</span>
              <span class="button">{{ o.edit_time_display }}</span>
              <span v-show="o.state === 0" class="button" style="color:red;margin-right: 10px;cursor:pointer" @click="to_change_state(o)">未解决</span>
              <span v-show="o.state === 1" class="button" style="color:#67C23A;margin-right: 10px;">已解决</span>
              <span v-show="o.state === 2" class="button" style="color:#409EFF;margin-right: 10px;cursor:pointer" @click="to_change_state(o)">{{ auth==='developer'?'确认已解决':'等待确认' }}</span>
            </div>
            <hr style="height:1px;border:0;background-color: #DCDFE6;">
          </div>
        </div>
      </el-form-item>
      <el-form-item label="文档名称" prop="doc_title">
        <el-input v-model="form.doc_title" />
      </el-form-item>
      <el-form-item label="MessageType" prop="message_type">
        <el-input v-model="form.message_type" />
      </el-form-item>
      <el-form-item label="关联表" prop="tables">
        <el-select v-model="form.tables" filterable placeholder="请选择关联表" multiple style="width: 100%" :filter-method="filter">
          <el-option
            v-for="item in tables"
            :key="item.table_name"
            :label="item.engine"
            :value="item.table_name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="参数" prop="params">
        <el-tabs type="border-card">
          <el-tab-pane label="JSON" class="tab">
            <el-input v-model="form.params" type="textarea" :autosize="true" />
          </el-tab-pane>
          <el-tab-pane label="参数说明" class="tab">
            <api-table
              name="params"
              :data="tableData_params"
              style="width: 100%;margin-bottom: 20px;"
            />
          </el-tab-pane>
        </el-tabs>
      </el-form-item>
      <el-form-item label="返回值" prop="returns">
        <el-tabs type="border-card">
          <el-tab-pane label="JSON" class="tab">
            <el-input v-model="form.returns" type="textarea" :autosize="true" />
          </el-tab-pane>
          <el-tab-pane label="返回值说明" class="tab">
            <api-table
              name="results"
              :data="tableData_results"
              style="width: 100%;margin-bottom: 20px;"
            />
          </el-tab-pane>
        </el-tabs>
      </el-form-item>
      <el-form-item label="更新信息" prop="message">
        <el-input v-model="form.message" placeholder="请输入更新信息" />
      </el-form-item>
      <el-form-item>
        <el-button :loading="test_loading" type="primary" @click="test">测试</el-button>
        <el-button v-show="!!auth" :loading="sure_loading" type="primary" @click="submitForm">{{ docId?'更新':'保存' }}</el-button>
        <el-button
          v-clipboard:copy="export_markdown()"
          v-clipboard:success="onCopy"
          v-clipboard:error="onError"
        >导出Markdown</el-button>
        <el-button @click="generator">表单生成器</el-button>
        <el-button @click="goback">取消</el-button>
      </el-form-item>
    </el-form>

    <make-question ref="make-question" :visible="make_question_display" @dialog-close="make_question_display = false" @dialog-sure="dialog_sure" />
  </div>
</template>

<script>
import { get, set } from '@/utils/storage'
import apiTable from './api-table'
import { test_api, add, find_one_api, edit, change_state } from '../api'
import tree_data from '@/utils/tree-data'
import keep_data from '../atom/keep-data'
import makeQuestion from './make-question'
import markdown from '@/utils/markdwon'
import { take_array } from '@/utils/keep-data'

export default {
  components: {
    apiTable,
    makeQuestion
  },
  props: {
    levels: {
      type: Array,
      default: () => []
    },
    docId: {
      type: String,
      default: ''
    },
    spaceId: {
      type: String,
      default: ''
    },
    projectId: {
      type: String,
      default: ''
    },
    clientType: {
      type: String,
      default: ''
    }
  },
  data: function() {
    const validate_params = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入请求参数'))
      } else {
        try {
          JSON.parse(value)
          callback()
        } catch (error) {
          callback(new Error('请确保参数为JSON格式'))
        }
      }
    }
    return {
      tables: [],
      // levels: [],
      logs: [],
      form: {
        doc_title: '',
        message_type: '',
        tables: [],
        params: '',
        returns: '',
        message: ''
      },
      rules: {
        doc_title: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        message_type: [{ required: true, message: '请输入MessageType', trigger: 'blur' }],
        params: [{ required: true, trigger: 'blur', validator: validate_params }]
        // message: [{ required: true, message: '请输入更新日志', trigger: 'blur' }]
      },
      results: {
        request: [],
        response: []
      },
      tableData_params: [],
      tableData_results: [],
      test_loading: false,
      sure_loading: false,
      auth: '',
      make_question_display: false
    }
  },
  created() {
    this.render_level()
    this.render_tables()
    this.render_form()
  },
  methods: {
    render_level() {
      this.auth = get('role')
    },
    render_tables() {
      const project_id = this.projectId
      this.tables = JSON.parse(get(project_id))
    },
    render_form() {
      if (this.docId) {
        this.form.message = ''
        find_one_api(this.docId).then((res) => {
          this.form.message_type = res.data.message_type
          this.form.doc_title = res.data.doc_title
          this.form.tables = JSON.parse(res.data.tables)
          this.form.params = JSON.stringify(JSON.parse(res.data.params), null, '\t')
          this.logs = res.logs
          this.update(res.params, res.returns, JSON.parse(res.data.returns))
        })
        return
      } else {
        this.form.message = '新建服务'
      }
    },
    filter(label) {
      if (!label) {
        this.render_tables()
      }
      this.tables = this.tables.filter((tab) => {
        const table_name = tab.table_name.toLowerCase()
        const engine = tab.engine.toLowerCase()
        const _label = label.toLowerCase()
        return table_name.indexOf(_label) !== -1 || engine.indexOf(_label) !== -1
      })
    },
    submitForm() {
      if (this.docId && !this.form.message) {
        this.$message({
          message: '请输入更新信息',
          type: 'warning',
          duration: 2 * 1000
        })
        return
      }
      //
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (!this.form.returns) {
            this.$message({
              message: '请先点击测试按钮，对接口进行测试',
              type: 'error',
              duration: 2 * 1000
            })
            return
          }
          this.sure_loading = true
          // 保存之前会再测试一下接口，但是不再更新页面数据
          // this.testmodel().then((res) => {
          const parent_id = this.levels[this.levels.length - 1].doc_id
          if (this.docId) {
            edit(this.docId, this.form.doc_title, this.form.message, this.form.tables, JSON.parse(this.form.params), JSON.parse(this.form.returns), this.tableData_params, this.tableData_results).then((res) => {
              this.sure_loading = false
              this.$emit('edit-success')
              this.$confirm('修改成功', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then((ret) => {
                // 用户确认
              }).catch(() => {
                // 用户取消
              })
            })
            return
          } else {
            add(this.projectId, this.spaceId, this.clientType, parent_id, this.form.doc_title, this.form.tables, this.form.message_type, JSON.parse(this.form.params), JSON.parse(this.form.returns), this.tableData_params, this.tableData_results).then((res) => {
              this.sure_loading = false
              this.$emit('edit-success')
            }).catch((err) => {
              this.sure_loading = false
              console.warn(err)
              this.$message({
                message: '服务出错，打开控制台查看具体信息',
                type: 'success',
                duration: 2 * 1000
              })
              return
            })
          }
        }
      })
    },
    goback() {
      // this.$router.back()
      this.$emit('edit-cancel')
    },
    test() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm('请谨慎测试删除功能', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then((ret) => {
            this.test_loading = true
            this.testmodel().then((res) => {
              this.$message({
                message: '测试成功',
                type: 'success',
                duration: 2 * 1000
              })
              this.update(res.request, res.response, res.data)
              this.test_loading = false
            }).catch((err) => {
              this.test_loading = false
              console.warn(err)
              this.$message({
                message: '服务出错，打开控制台查看具体信息',
                type: 'success',
                duration: 2 * 1000
              })
            })
          })
        }
      })
    },
    update(request_data, response_data, data) {
      const request = keep_data(this.tableData_params, request_data)
      const response = keep_data(this.tableData_results, response_data)
      this.tableData_params = tree_data(request, 'parent_id', 'prop_id')
      this.tableData_results = tree_data(response, 'parent_id', 'prop_id')
      this.form.returns = JSON.stringify(data, null, '\t')
    },
    testmodel() {
      const tables = this.form.tables
      const params = this.form.params
      const message_type = this.form.message_type
      const doc_title = this.form.doc_title
      const sessionid = get('sessionid')
      return test_api(sessionid, this.projectId, doc_title, message_type, params, tables)
    },
    make_question() {
      this.make_question_display = true
      this.$refs['make-question'].show(this.docId)
    },
    dialog_sure() {
      this.make_question_display = false
      this.render_form()
    },
    onCopy: function(e) {
      this.$message({
        message: '拷贝成功',
        type: 'success',
        duration: 2 * 1000
      })
      return
    },
    onError: function(e) {
      alert('Failed to copy texts')
    },
    to_change_state(row) {
      const state = row.state
      const user = get('user_code')
      // const role = get('role')
      // if (role === 'developer' && state === 0) {
      //   this.$message({
      //     message: '请通知开发者解决',
      //     type: 'warning',
      //     duration: 2 * 1000
      //   })
      //   return
      // } else if (role === 'maintainer' && state === 2) {
      //   this.$message({
      //     message: '请通知使用者确认',
      //     type: 'warning',
      //     duration: 2 * 1000
      //   })
      //   return
      // }
      this.$confirm((() => {
        if (state === 0) {
          return '已解决？'
        } else if (state === 2) {
          return '确认已解决？'
        }
      })(), {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((ret) => {
        // 用户确认
        const _state = (() => {
          if (state === 0) {
            return '2'
          } else if (state === 2) {
            return '1'
          }
        })()
        change_state(row.question_id, _state, user).then(() => {
          this.render_form()
        })
      }).catch(() => {
        // 用户取消
      })
    },
    // 导出markdwon
    export_markdown() {
      // 文档名称，MessageType, 参数, 返回值
      const res = markdown(this.form.doc_title, this.form.message_type, this.form.params, this.tableData_params, this.form.returns, this.tableData_results, this.logs)
      return res
    },
    generator() {
      const f1 = Array.from(take_array(this.tableData_params, new Map()).values()).filter((i) => {
        return i.note
      }).map((j) => {
        return {
          label: j.note,
          value: j.prop
        }
      })
      const f2 = Array.from(take_array(this.tableData_results, new Map()).values()).filter((i) => {
        return i.note
      }).map((j) => {
        return {
          label: j.note,
          value: j.prop
        }
      })
      set('filelds', JSON.stringify(f1.concat(f2)))
      window.open('http://192.168.1.238/form-generator', '_blank')
    }
  }
}
</script>

<style lang="scss" scoped>

.tab {
  input {
    height: 100%;
  }
}
.card-content {
  margin-bottom: 0;
  &:last-child {
    .divider {
      display: none;
    }
  }
}

  .button {
    padding: 0;
    float: right;
    color: #409EFF;
    font-size: 14px;
  }

.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
}

.clearfix:after {
    clear: both
}
</style>
